import { defineStore } from 'pinia'
import { ref } from 'vue'
import { removeToken } from '@/composables/auth'
import { getUserInfo } from '@/api/manager'

export const useUserStore = defineStore(
  'user',
  () => {
    // 用户信息
    const user = ref()
    // 侧边栏宽度
    const asidWidth = ref('180px')
    // 菜单列表
    const menus = ref([])
    // 权限名数组
    const ruleNames = ref([])
    // 左侧菜单层级
    const zIndex = ref(0)
    // 头部层级
    const headerIndex = ref(1)
    // 高级搜索
    const showSearch = ref(false)
    // 保存用户信息
    const setUser = payload => {
      user.value = payload
    }
    // 退出登录
    const userLogout = () => {
      // 删除 cookie
      removeToken()
      user.value = {}
    }
    // 设置侧边栏宽度
    const setAsidWidth = () => {
      asidWidth.value = asidWidth.value == '180px' ? '64px' : '180px'
    }
    // 设置菜单
    const setMenus = menu => {
      menus.value = menu
    }
    // 设置权限名
    const setRuleNames = rulename => {
      ruleNames.value = rulename
    }
    // 获取当前用户登录信息
    const getInfo = () => {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          setUser(res)
          setMenus(res.menus)
          setRuleNames(res.ruleNames)
          resolve(res)
        })
          .catch(err => reject(err))
      })
    }
    return {
      user,
      menus,
      zIndex,
      headerIndex,
      ruleNames,
      asidWidth,
      showSearch,
      setUser,
      userLogout,
      setAsidWidth,
      setMenus,
      setRuleNames,
      getInfo
    }
  },
  {
    persist: true,
  }
)
